package main

import (
	"bufio"
	"fmt"
	"os"
	"time"

	"github.com/github-user/hw4/read_ini"
)

type ListenFunc func(string)

func (l ListenFunc) Listen(inifile string) {
	l(inifile)
}

func main() {
	var lis ListenFunc = func(inifile string) {
		before_info, err := os.Lstat(inifile)
		if err != nil {
			panic(err)
		}
		for {
			after_info, err := os.Lstat(inifile)
			if err != nil {
				panic(err)
			}
			if !before_info.ModTime().Equal(after_info.ModTime()) {
				fmt.Println("There are something changed in file ", inifile)
				break
			}
			fmt.Println("Listening changes in file ", inifile)
			time.Sleep(time.Duration(1) * time.Second)
		}
	}
	go func() {
		read_ini.Init()
		for {
			conf, err := read_ini.Watch("../example.ini", lis)
			if err != nil {
				fmt.Println(err)
			}
			for s, _ := range conf {
				fmt.Println("Section: ", s)
				for _, value := range conf[s] {
					for k, v := range value {
						fmt.Println("Key:", k, "\tValue:", v)
					}
				}
				fmt.Println()
			}
		}
	}()
	time.Sleep(time.Duration(3) * time.Second)
	i := 0
	file, openErr := os.OpenFile("../example.ini", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
	if openErr != nil {
		panic(openErr)
	}
	writer := bufio.NewWriter(file)
	_, errWrite := writer.Write([]byte("[test]\n"))
	if errWrite != nil {
		panic(errWrite)
	}
	writer.Flush()
	for {
		_, errWrite = writer.Write([]byte(fmt.Sprintf("Test_key%d = Test_value%d\n", i, i)))
		i += 1
		if errWrite != nil {
			panic(errWrite)
		}
		writer.Flush()
		time.Sleep(time.Duration(3) * time.Second)
	}
}
